<script setup lang="ts">
import {
  Modal,
  Form,
  FormItem,
  FormInstance,
  Input,
  InputPassword,
  message,
} from "ant-design-vue";
import { Service, UserInfoInput } from "../api";
import { ref, reactive, watch } from "vue";
const open = defineModel<boolean>("open", { required: true });
const emits = defineEmits<{
  finish: [];
  toLogin: [];
}>();

const formRef = ref<FormInstance>();
const formState = reactive<Partial<UserInfoInput>>({});
const loading = ref(false);
const register = async () => {
  loading.value = true;
  try {
    await formRef.value?.validate();
    await Service.register({
      input: formState as UserInfoInput,
    });
    message.success("注册成功");
    emits("finish");
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
watch(open, () => {
  if (open) {
    formRef.value?.resetFields();
  }
});
</script>
<template>
  <Modal
    v-model:open="open"
    title="用户注册"
    @ok="register"
    ok-text="注册"
    cancel-text="取消"
    :confirmLoading="loading"
  >
    <div style="text-align: right; font-size: 12px; padding: 5px 10px 10px 0px">
      已有账号? 去<a @click="emits('toLogin')">登录</a>
    </div>
    <Form
      ref="formRef"
      :model="formState"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <FormItem
        label="姓名"
        name="name"
        :rules="[{ required: true, message: '姓名不能为空' }]"
      >
        <Input v-model:value="formState.name" />
      </FormItem>
      <FormItem
        label="用户名"
        name="username"
        :rules="[{ required: true, message: '用户名不能为空' }]"
      >
        <Input v-model:value="formState.username" />
      </FormItem>
      <FormItem
        label="密码"
        name="password"
        :rules="[{ required: true, message: '密码不能为空' }]"
      >
        <InputPassword v-model:value="formState.password" />
      </FormItem>
    </Form>
  </Modal>
</template>
